package com.sanjiayi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanjiayi.mapper.CommentMapper;
import com.sanjiayi.mapper.MomentMapper;
import com.sanjiayi.pojo.Comment;
import com.sanjiayi.pojo.Moment;
import com.sanjiayi.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class  CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private MomentMapper momentMapper;

    @Override
    @Transactional
    public Comment addComment(Comment comment) {
        // 检查动态是否存在
        Moment moment = momentMapper.selectById(comment.getMomentId());
        if (moment == null) {
            throw new RuntimeException("动态不存在");
        }

        // 添加评论
        commentMapper.insert(comment);
        
        // 更新评论数
        momentMapper.updateCommentCount(comment.getMomentId(), 1);
        
        return comment;
    }

    @Override
    public List<Comment> getCommentsByMomentId(Integer momentId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("moment_id", momentId)
                   .orderByDesc("create_time");
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    public int getCommentCount(Integer momentId) {
        Integer count = momentMapper.getCommentCount(momentId);
        return count != null ? count : 0;
    }
} 